package com.lagou.dao.impI;

import com.lagou.dao.AccountDao;
import com.lagou.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Author wsl
 * @Date 2021/11/14 19:16
 * @Project_Name jdbc_spring
 */
@Repository
public class AccountDaoImpI implements AccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 1.查询所有
     * @return
     */
    public List<Account> findAll() {
        //要用到JdbcTemplate
        String sql = "select * from account";
        List<Account> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Account>(Account.class));
        return list;
    }

    /**
     * 2.根据ID查询
     * @param id
     * @return
     */
    public Account findById(Integer id) {
        String sql = "select * from account where id = ?";
        Account account = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Account>(Account.class), id);
        return account;
    }

    /**
     * 3.添加操作
     * @param account
     */
    public void save(Account account) {
        String sql = "insert into account values(null,?,?)";
        jdbcTemplate.update(sql,account.getName(),account.getMoney());
    }

    /**
     * 4.更新操作
     * @param account
     */
    public void update(Account account) {
        String sql = "update account set money = ? where name = ?";
        jdbcTemplate.update(sql,account.getMoney(),account.getName());
    }

    /**
     * 5.删除操作
     * @param id
     */
    public void delete(Integer id) {
        String sql = "delete from account where id = ?";
        jdbcTemplate.update(sql,id);
    }
}
